package com.ruoyi.video.server.onvif;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.video.domain.OnvifCamera;
import com.ruoyi.video.domain.VideoCamera;
import com.ruoyi.video.server.onvif.lib.DiscoveryDevice;
import com.ruoyi.video.server.onvif.lib.OnvifApi;
import com.ruoyi.video.server.push.PushMessage;
import com.ruoyi.video.server.push.PushServer;
import com.ruoyi.video.service.IVideoCameraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 发现设备后进行登录操作
 */
@Slf4j
@Service
public class DiscoveryDeviceImpl extends DiscoveryDevice {
    public static Map<String, OnvifCamera> cameraMap = new ConcurrentHashMap<>();

    @Autowired
    private IVideoCameraService videoCameraService;
    @Autowired
    private PushServer pushServer;

    /**
     * 发现新设备
     * @param ip
     */
    public void onDevice(String ip) {
        if(ip.equalsIgnoreCase("127.0.0.1") || ip.equalsIgnoreCase(IpUtils.getHostIp())){
            return;
        }
        OnvifCamera camera = cameraMap.get(ip);
        if(camera == null){
            log.info("发现新的onvif设备:{}", ip);
            camera = new OnvifCamera();
            camera.setIp(ip);
            camera.setPort(80);
            camera.setLastTime(System.currentTimeMillis());
            if(camera.getCameraId() == null){
                VideoCamera videoCamera = videoCameraService.selectVideoCameraByIp(ip, "onvif");
                if(videoCamera != null){
                    camera.setCameraId(videoCamera.getId());
                    if(videoCamera.getOnline().equalsIgnoreCase("N")){
                        //离线变在线
                        videoCamera.setOnline("Y");
                        videoCameraService.updateVideoCamera(videoCamera);
                        pushServer.push(PushMessage.DEVICE_ONLINE, videoCamera.getId(), videoCamera);
                    }
                    camera.setCameraOnline("Y");
                }else{
                    camera.setCameraId(-1L);
                }
            }

            cameraMap.put(ip, camera);
        }else{
            camera.setLastTime(System.currentTimeMillis());
            if(camera.getCameraId() == null){
                VideoCamera videoCamera = videoCameraService.selectVideoCameraByIp(ip, "onvif");
                if(videoCamera != null){
                    camera.setCameraId(videoCamera.getId());
                    camera.setCameraOnline(videoCamera.getOnline());
                }
            }
        }
    }

    /**
     * 尝试登录
     * @param userName
     * @param password
     * @return
     */
    public void tryLogin(String userName, String password){
        for(OnvifCamera camera:cameraMap.values()){
            if(camera.getToken() == null){
                continue;
            }else{
                camera.setUsername(userName);
                camera.setPassword(password);
                //如果登录失败就重置为空
                if(StringUtils.isEmpty(getInfo(camera))){
                    camera.setUsername(null);
                    camera.setPassword(null);
                }
            }
        }
    }



    /**
     * 登录设备并获取详细
     * @param camera
     */
    private String getInfo(OnvifCamera camera){
        try {
            OnvifApi onvifApi = SpringUtils.getBean(OnvifApi.class);
            String token = onvifApi.getToken(camera);
            if (token != null) {
                log.info("登录ONVIF设备{}成功，将获取详细失败", camera.getIp());
                camera.setLoginTime(System.currentTimeMillis());
                camera.setToken(token);
                onvifApi.getInfo(camera);
                onvifApi.stream(camera);
            } else {
                camera.setError("登录失败");
                log.error("登录ONVIF设备{}失败", camera.getIp());
            }
            return token;
        }catch (Exception e){
            e.printStackTrace();
            log.error("初始化ONVIF摄像机 {}失败：\r\n{}", camera.getIp(), e.getMessage());
        }
        return null;
    }
}
